package com.scsj.cloud.base.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;


/**
 * 全局过滤器(前端重复请求过滤)
 * @author caoxiubin
 * @date 2019年04月28日
 *
 */
public class HttpAuthorizeFilter implements Filter {
	
	private List<String> allowedPaths = new ArrayList<>();
	
	private Logger logger =  LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@Override
	public void destroy() {
		
	}
	
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		
		//定义请求对象，用来获取客户端信息
		HttpServletRequest httpRequest = (HttpServletRequest)req;
		//定义返回对象，用来向客户端返回验证失败信息
        HttpServletResponse httpResp = (HttpServletResponse)resp;
        httpResp.setCharacterEncoding("UTF-8");
        httpResp.setContentType("application/json;charset=utf-8");
        //httpResp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        
        // 获取当前接口请求路径
     	String requestUrl = httpRequest.getRequestURI();
     	logger.info("当前请求接口路径=====》"+requestUrl);
     	// 获取当前请求IP
     	String requestIp = httpRequest.getRemoteHost();
     	logger.info("当前请求IP=====》"+requestIp);
     	
     	// 白名单中是否包含该请求URL
     	boolean isAllowed = allowedPaths.contains(requestUrl);
     	
     	if(isAllowed) {
     		// 将前端请求放行
     		httpResp.setStatus(200);
            chain.doFilter(req, resp);
     	}else {
     		
     		// 客户端token验证
            String clientToken = httpRequest.getHeader("token");
            logger.info("clientToken=====>"+clientToken);
            if(clientToken==null || "null".equals(clientToken) || "".equals(clientToken)) {
            	// 与前端约定返回的字符串内容
            	String responseStr = "{\"msg\":\"token未找到！您没有访问权限！\",\"status\":\"401\"}";
            	httpResp.getWriter().write(responseStr);return;
            }
            
            // 服务端token验证
            String serverToken = stringRedisTemplate.opsForValue().get(clientToken);
            // logger.info("serverToken=====>"+serverToken);
            if(serverToken==null) {
            	// 与前端约定返回的字符串内容
            	String responseStr = "{\"msg\":\"token已经过期！请您重新登录！\",\"status\":\"401\"}";
            	httpResp.getWriter().write(responseStr);return;
            }
            
            httpResp.setStatus(200);
            logger.info("开始放行===================================>");
            // 将前端请求放行
            chain.doFilter(req, resp);
            logger.info("已经放行===================================>");
     	}
     	
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		
		allowedPaths.add("/scsj/cloud/authority/public/login");//登录
		allowedPaths.add("/scsj/cloud/authority/user/findLoginInfoByToken");
		SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
	}

}
